package com.czzapp.xiaoyumemo.view;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.czzapp.xiaoyumemo.R;
import com.czzapp.xiaoyumemo.model.Memo;
import com.czzapp.xiaoyumemo.model.Memo.MemoState;
import com.czzapp.xiaoyumemo.model.MemoManager;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.InputFilter;
import android.text.format.DateUtils;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TimePicker;
import android.widget.Toast;

enum Status
{
	STOP,
	RECORDING,
	PLAY,
	PLAY_PAUSE
}
//添加和修改备忘的界面
public class EditingMemoActivity extends Activity {
	
	private ImageView mImg = null;
	private Button mButtonDate = null;
	private Button mButtonTime = null;
	private Button mButtonSave = null;
	//private TextView mTextTime = null;
	private EditText mEdittextName = null;
	private ImageButton mButtonRecord_Pause = null;
	private ImageButton mButtonPlay_Stop = null;
	private Calendar mCalendar = null;
	private String weekStrArr1[] = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
	private String ampmStrArr2[] = {"上午","下午"};
	private Status mStatus = Status.STOP;
	private Memo mMemo = null;
	
	public MediaPlayer mMediaPlayer;
	AudioManager audiomanager;
	private MediaRecorder mMediaRecorder;
	private String strTempFile = "xiaoyurec_";
	private File mRecFile = null;
	
	private Handler mHandler = null;
	private Runnable mRunnable = null;
	private Runnable mRunnableReduce = null;
	private Runnable mRunableComplete = null;
	private int mTimeCount = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.editing_memo);
		Intent intent = getIntent();
		int id = intent.getIntExtra("MemoId", -1);
		String date = intent.getStringExtra("Date");
		
		mImg = (ImageView)findViewById(R.id.image);
		mButtonDate = (Button)findViewById(R.id.buttonDate);
		mButtonTime = (Button)findViewById(R.id.buttonTime);
		mButtonSave = (Button)findViewById(R.id.edit_memo_Save);
		mEdittextName = (EditText)findViewById(R.id.edittextName);
		mEdittextName.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)});
		//mTextTime = (TextView)findViewById(R.id.textTime);
		mButtonRecord_Pause = (ImageButton)findViewById(R.id.edit_memo_Record);
		mButtonPlay_Stop = (ImageButton)findViewById(R.id.edit_memo_Play);
		//初始化
		mCalendar = Calendar.getInstance();
		if(date != null)
		{
			if(date.compareTo("") != 0)
			{
				SimpleDateFormat   df=new   SimpleDateFormat( "yyyy-MM-dd"); 
				Date d = null;
				try {
					d = df.parse(date);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 			
				if(d != null)
				{
					mCalendar.setTime(d);
					mCalendar.set(Calendar.HOUR, Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
				}
			}
		}
		//清空秒数
		mCalendar.set(Calendar.SECOND, 0);
		if(id == -1)
		{
			
		}
		else
		{
			mMemo = MemoManager.getInstance().getMemoById(id);
			if(mMemo.getState() == MemoState.Missed)
			{
				MemoManager.getInstance().checkMemo(mMemo);
			}
			mEdittextName.setText(mMemo.getTitle());
			mCalendar.setTime(mMemo.getInitdate());
			mRecFile = new File(mMemo.getAudioPath());
		}
		mButtonDate.setText(mCalendar.get(Calendar.YEAR) + "年"+(mCalendar.get(Calendar.MONTH)+1) + "月" + mCalendar.get(Calendar.DAY_OF_MONTH) +"日" +weekStrArr1[mCalendar.get(Calendar.DAY_OF_WEEK) - 1]);
		String hour = "";
    	if(mCalendar.get(Calendar.HOUR) >= 10)
    	{
    		hour = Integer.toString(mCalendar.get(Calendar.HOUR));
    	}
    	else
    	{
    		hour = "0" + mCalendar.get(Calendar.HOUR);
    	}
    	String minuteStr = "";
    	if(mCalendar.get(Calendar.MINUTE) >= 10)
    	{
    		minuteStr = Integer.toString(mCalendar.get(Calendar.MINUTE));
    	}
    	else
    	{
    		minuteStr = "0" + mCalendar.get(Calendar.MINUTE);
    	}
		mButtonTime.setText(ampmStrArr2[mCalendar.get(Calendar.AM_PM)] + hour + ":" + minuteStr);
		
		
		//录音

		audiomanager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		audiomanager.setMode(AudioManager.MODE_NORMAL);

		//计时
		mHandler = new Handler();
		mRunnable = new Runnable() {
			
			@Override
			public void run() {
				mTimeCount++;
				MaomaoSheck();
				//UpdateTime();
				mHandler.postDelayed(this, 500);  
			}
		};
		mRunnableReduce = new Runnable() {
			
			@Override
			public void run() {
				mTimeCount--;
				MaomaoSheck();
				//UpdateTime();
				mHandler.postDelayed(this, 500); 
			}
		};
		mRunableComplete = new Runnable() {
			
			@Override
			public void run() {
				mImg.setImageResource(R.drawable.mao1);
				//mTextTime.setText("00:00");
			}
		};
		mButtonDate.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				
				 new DatePickerDialog(EditingMemoActivity.this,  
	                        new DatePickerDialog.OnDateSetListener() {  
	                              	                         
								@Override
								public void onDateSet(DatePicker arg0,
										int arg1, int arg2, int arg3) {
									
									mCalendar.set(arg1, arg2, arg3);
									mButtonDate.setText(mCalendar.get(Calendar.YEAR) + "年"+(mCalendar.get(Calendar.MONTH)+1) + "月" + mCalendar.get(Calendar.DAY_OF_MONTH) +"日" +weekStrArr1[mCalendar.get(Calendar.DAY_OF_WEEK) - 1]);
								}  
	                        },mCalendar.get(Calendar.YEAR),mCalendar.get(Calendar.MONTH),mCalendar.get(Calendar.DAY_OF_MONTH)).show();  
			}
		});
		
		
		mButtonTime.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				
				 new TimePickerDialog(EditingMemoActivity.this,  
	                        new TimePickerDialog.OnTimeSetListener() {  
	                              
	                            @Override  
	                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {  
	                                
	                                //设置时间  
	                            	mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
	                            	mCalendar.set(Calendar.MINUTE, minute);
	                            	String hour = "";
	                            	if(mCalendar.get(Calendar.HOUR) >= 10)
	                            	{
	                            		hour = Integer.toString(mCalendar.get(Calendar.HOUR));
	                            	}
	                            	else
	                            	{
	                            		hour = "0" + mCalendar.get(Calendar.HOUR);
	                            	}
	                            	String minuteStr = "";
	                            	if(mCalendar.get(Calendar.MINUTE) >= 10)
	                            	{
	                            		minuteStr = Integer.toString(mCalendar.get(Calendar.MINUTE));
	                            	}
	                            	else
	                            	{
	                            		minuteStr = "0" + mCalendar.get(Calendar.MINUTE);
	                            	}
	                            	mButtonTime.setText(ampmStrArr2[mCalendar.get(Calendar.AM_PM)] + hour + ":" + minuteStr);
	                            }								 
	                        },mCalendar.get(Calendar.HOUR_OF_DAY),mCalendar.get(Calendar.MINUTE),false).show();  
			}
		});
		mButtonRecord_Pause.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(mStatus == Status.STOP)
				{
					
					File recPath ;
					if (Environment.getExternalStorageState().equals(
							android.os.Environment.MEDIA_MOUNTED)) {
						recPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/" +  getResources().getText(R.string.sd_head));
						if(!recPath.exists())
						{
							recPath.mkdir();
						}
					} else {
						Toast.makeText(EditingMemoActivity.this, "没有SD卡",
								Toast.LENGTH_LONG).show();
						return;
					}
					try {
						File recFile = File.createTempFile(strTempFile, ".amr",recPath);
						if(Record(recFile))
						{
							mRecFile = recFile;
							mButtonRecord_Pause.setImageResource(R.drawable.button_stop);
							mButtonPlay_Stop.setVisibility(View.GONE);
							mStatus = Status.RECORDING;
							mTimeCount = 0;
							mHandler.postDelayed(mRunnable, 500); 							
						}
					} catch (IOException e) {
						
						e.printStackTrace();
						return;
					}				
				}
				else if(mStatus == Status.RECORDING)
				{
					mMediaRecorder.stop();
					mMediaRecorder.release();
					mHandler.removeCallbacks(mRunnable);
					mHandler.postDelayed(mRunableComplete, 0);
					mMediaRecorder = null;
					mButtonRecord_Pause.setImageResource(R.drawable.button_record);
					mButtonPlay_Stop.setVisibility(View.VISIBLE);
					mStatus = Status.STOP;
					//mTextTime.setText("00:00");
				}
				else if(mStatus == Status.PLAY_PAUSE)
				{			
					File recPath ;
					if (Environment.getExternalStorageState().equals(
							android.os.Environment.MEDIA_MOUNTED)) {
						recPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/" + getResources().getText(R.string.sd_head));
						if(!recPath.exists())
						{
							recPath.mkdir();
						}
					} else {
						Toast.makeText(EditingMemoActivity.this, "没有SD卡",
								Toast.LENGTH_LONG).show();
						return;
					}
					try {
						
						File recFile = File.createTempFile(strTempFile, ".3pg",recPath);
						if(Record(recFile))
						{
							mRecFile= recFile;
							mButtonRecord_Pause.setImageResource(R.drawable.button_stop);
							mButtonPlay_Stop.setVisibility(View.GONE);
							mStatus = Status.RECORDING;
							mTimeCount = 0;
							mHandler.postDelayed(mRunnable, 500);
						}
					} catch (IOException e) {
						
						e.printStackTrace();
						return;
					}		
				}				
			}
		});
		mButtonPlay_Stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(mStatus == Status.RECORDING)
				{
					
				}
				else if(mStatus == Status.STOP)
				{
					if(mRecFile != null && mRecFile.exists())
					{
						if(PlayAudio(mRecFile))
						{
							mTimeCount = mMediaPlayer.getDuration()/1000;
							//UpdateTime();
							mHandler.postDelayed(mRunnableReduce, 500);
							mButtonPlay_Stop.setImageResource(R.drawable.button_pause);	
							mButtonRecord_Pause.setVisibility(View.GONE);
							mStatus = Status.PLAY;
						}
					}
					else
					{
						Toast.makeText(EditingMemoActivity.this, "请您先录制音频", Toast.LENGTH_SHORT).show();
					}
				}
				else if(mStatus == Status.PLAY_PAUSE)
				{
//					mTimeCount = mMediaPlayer.getCurrentPosition()/1000;
//					UpdateTime();
					mHandler.postDelayed(mRunnableReduce, 500);
					mMediaPlayer.start();
					mButtonPlay_Stop.setImageResource(R.drawable.button_pause);
					mButtonRecord_Pause.setVisibility(View.GONE);
					mStatus = Status.PLAY;
				}
				else if(mStatus == Status.STOP)
				{
					
				}
				else if(mStatus == Status.PLAY)
				{
					mMediaPlayer.pause();
					mButtonPlay_Stop.setImageResource(R.drawable.button_play);
					mButtonRecord_Pause.setVisibility(View.VISIBLE);
					mStatus = Status.PLAY_PAUSE;
					mHandler.removeCallbacks(mRunnableReduce);
					mHandler.postDelayed(mRunableComplete, 500);
				}
			}
		});
		mButtonSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				try {
					mStatus = Status.STOP;
					if(mMediaRecorder != null)
					{
						mMediaRecorder.stop();
						mMediaRecorder.release();
					}
					if(mMediaPlayer != null)
					{
						mMediaPlayer.stop();
						mMediaRecorder.release();
					}
				} catch (Exception e) {
					mStatus = Status.STOP;
				}
				String temp = mEdittextName.getText().toString();
				if(mRecFile != null && mRecFile.exists())
				{
					if(temp.compareTo("") == 0)
					{
						//String dateStr = (String)DateUtils.formatDateTime(EditingMemoActivity.this, mCalendar.getTimeInMillis(), DateUtils.FORMAT_SHOW_DATE);
						mEdittextName.setText(mCalendar.getTime().toString());
					}
					if(mMemo == null)
					{
						MemoManager.getInstance().addMemo(mEdittextName.getText().toString(), "", mRecFile.getAbsolutePath(), mCalendar.getTime());
					}
					else
					{						
						if(mMemo.getState() == MemoState.Coming)
						{
							
							mMemo.setTitle(temp);
							mMemo.setAudioPath(mRecFile.getAbsolutePath());
							MemoManager.getInstance().upateMemo(mMemo, mCalendar.getTime());
						}
						else
						{
							MemoManager.getInstance().addMemo(mEdittextName.getText().toString(), "", mRecFile.getAbsolutePath(), mCalendar.getTime());
							//MemoManager.getInstance().deleteMemo(mMemo);
						}
					}
					EditingMemoActivity.this.finish();
				}
				else
				{
					Toast.makeText(EditingMemoActivity.this, "您还没有录制音频呢", Toast.LENGTH_SHORT).show();
				}
//				if(temp.compareTo("") != 0)
//				{
//					if(mRecFile != null && mRecFile.exists())
//					{
//						if(mMemo == null)
//						{
//							MemoManager.getInstance().addMemo(mEdittextName.getText().toString(), "", mRecFile.getAbsolutePath(), mCalendar.getTime());
//						}
//						else
//						{
//							if(mMemo.getState() == MemoState.Coming)
//							{
//								mMemo.setTitle(mEdittextName.getText().toString());
//								mMemo.setAudioPath(mRecFile.getAbsolutePath());
//								MemoManager.getInstance().upateMemo(mMemo, mCalendar.getTime());
//							}
//							else
//							{
//								MemoManager.getInstance().addMemo(mEdittextName.getText().toString(), "", mRecFile.getAbsolutePath(), mCalendar.getTime());
//								//MemoManager.getInstance().deleteMemo(mMemo);
//							}
//						}
//						EditingMemoActivity.this.finish();
//					}
//					else
//					{
//						Toast.makeText(EditingMemoActivity.this, "您还没有录制音频呢", Toast.LENGTH_SHORT).show();
//					}
//				}
//				else
//				{
//					Toast.makeText(EditingMemoActivity.this, "请输入标题", Toast.LENGTH_SHORT).show();
//				}
			}
		});
	}
	public boolean Record(File recAudioFile)
	{
		try {
			if (Environment.getExternalStorageState().equals(
					android.os.Environment.MEDIA_MOUNTED)) {				
			} else {
				Toast.makeText(EditingMemoActivity.this, "没有SD卡",
						Toast.LENGTH_LONG).show();
				return false;
			}			
			mMediaRecorder = new MediaRecorder();
		
			mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mMediaRecorder
					.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			mMediaRecorder
					.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			
			mMediaRecorder.setOutputFile(recAudioFile.getAbsolutePath());
			
			mMediaRecorder.prepare();
			mMediaRecorder.start();
			
		} catch (IOException e) {
			return false;
		}
		return true;
	}
	public boolean PlayAudio(File audioFile)
	{
		try {
			mMediaPlayer = new MediaPlayer();
			mMediaPlayer.reset();
			try
			{			
				mMediaPlayer.setDataSource(audioFile.getAbsolutePath());				
				mMediaPlayer.prepare();
			}catch(IllegalStateException e){
				e.printStackTrace();
				return false;
			}catch(IOException e){
				e.printStackTrace();
				return false;
			}
		}
		catch(IllegalStateException e){
			e.printStackTrace();
			return false;
		}
		mMediaPlayer.start();					

		mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			
			public void onCompletion(MediaPlayer mp) {
				
				
				mMediaPlayer.release();
				mButtonPlay_Stop.setImageResource(R.drawable.button_play);
				mButtonRecord_Pause.setVisibility(View.VISIBLE);
				mStatus = Status.STOP;
				mTimeCount = 0;
				mHandler.removeCallbacks(mRunnableReduce);
				mHandler.post(mRunableComplete);
			}
		});
		return true;
	}
	private void MaomaoSheck()
	{
		if(mTimeCount%2 == 0)
		{
			mImg.setImageResource(R.drawable.mao1);
		}
		else
		{
			mImg.setImageResource(R.drawable.mao2);
		}
	}
//	public void UpdateTime()
//	{
//		if(mTimeCount > 60)
//		{
//			int minute = mTimeCount/60;
//			int second = mTimeCount%60;
//			if(minute < 10)
//			{
//				
//				if(second < 10)
//				{
//					mTextTime.setText("0" + minute + ":" + "0" + second);
//				}
//				else
//				{
//					mTextTime.setText("0" + minute + ":" + second);
//				}
//			}
//			else
//			{
//				if(second < 10)
//				{
//					mTextTime.setText(minute + ":" + "0" + second);
//				}
//				else
//				{
//					mTextTime.setText(minute + ":" + second);
//				}
//			}
//		}
//		else
//		{
//			if(mTimeCount < 10)
//			{
//				mTextTime.setText("00:" + "0" + mTimeCount);
//			}
//			else
//			{
//				mTextTime.setText("00:" + mTimeCount);
//			}
//		}
//	}
	@Override
	protected void onPause() {
		if(mStatus != Status.STOP)
		{
			try {
				if(mMediaRecorder != null)
				{
					mMediaRecorder.stop();
					mMediaRecorder.release();
					mHandler.removeCallbacks(mRunnable);			
				}
				if(mMediaPlayer != null)
				{
					mMediaPlayer.pause();
					mHandler.removeCallbacks(mRunnableReduce);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		super.onPause();
	}
	@Override
	protected void onResume() {
		
		super.onResume();
	}
}
